package com.example.onlinemusic.controller;

import com.example.onlinemusic.mapper.UserMapper;
import com.example.onlinemusic.model.User;
import com.example.onlinemusic.tools.Constant;
import com.example.onlinemusic.tools.ResponseBodyMessage;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.net.http.HttpRequest;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 均先生
 * Date: 2024-02-20
 * Time: 22:29
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @RequestMapping("/login")
    public ResponseBodyMessage<User> login(@RequestParam("username") String username,
                                           @RequestParam("password") String password, HttpServletRequest request) {
        User userLogin = userMapper.selectByName(username);
        userLogin.setUsername(username);
        userLogin.setPassword(password);
        System.out.println(userLogin);

        User user = userMapper.selectByName(username);
        if (user == null) {
            System.out.println("登录失败!");
            return new ResponseBodyMessage<>(-1,"登录失败",user);
        }else {
            boolean flg = bCryptPasswordEncoder.matches(password,user.getPassword());
            if (!flg) {
                return new ResponseBodyMessage<>(-1,"用户名或者密码错误!",user);
            }
            request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY,user);
            return new ResponseBodyMessage<>(1,"登录成功",user);
        }
    }
}
